﻿[Microsoft.AspNetCore.Mvc.Route("api/[controller]/[action]")]
    [ApiController]
    public class BaseController : ControllerBase
    {
        protected readonly IHttpContextAccessor _httpContextAccessor;

        public BaseController(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 获取当前UserID
        /// </summary>
        /// <returns></returns>
        protected string GetUser(string field)
        {
            try
            {
                ClaimsPrincipal claimsPrincipal = _httpContextAccessor.HttpContext.User;
                var claim = (claimsPrincipal)?.Claims.FirstOrDefault(c => c.Type == field);
                if (claim == null || string.IsNullOrEmpty(claim.Value))
                {
                    return "";
                }

                return claim.Value;
            }
            catch
            {
                return "";
            }
        }

        protected T ApiResultData<T>(ApiResult apiResult)
        {
            if (apiResult.code == 200)
            {
                return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(apiResult.data));
            }
            else
            {
                return default(T);
            }
        }
    }